package com.dayu.framework;

import java.net.SocketException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: PieceJob
 * @Description:TODO 线程处理模块
 * @author: 戴卫国
 * @date: 2018年2月23日 下午2:41:49
 * 
 * @Copyright: 2018 dayu Inc. All rights reserved.
 */
/**
 * @ClassName: PieceJob
 * @Description:TODO
 * @author: 戴卫国
 * @date: 2018年2月23日 下午2:44:14
 * 
 * @Copyright: 2018 dayu Inc. All rights reserved.
 */
public abstract class PieceJob implements Runnable {

	static Logger LOGGER = LoggerFactory.getLogger(PieceJob.class);

	/**
	 * @Title: init
	 * @Description: TODO 线程初始化
	 * @param: @throws
	 *             Exception
	 */
	public void init() throws Exception {
	}

	/**
	 * @Title: duration
	 * @Description: TODO 线程执行间隔时间
	 * @param: @return
	 */
	public int duration() {
		return 10000;
	}

	/**
	 * @Title: piece
	 * @Description: TODO
	 * @param: @throws
	 *             Exception
	 */
	public abstract void piece() throws Exception;

	/**
	 * <p>
	 * Title: run
	 * </p>
	 * <p>
	 * Description: 初始化init()=>执行piece()=>连接异常等待duration
	 * </p>
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {

		try {
			init();
		} catch (Exception e3) {
			throw new RuntimeException(e3);
		}

		LOGGER.info("Starting: " + this.getClass());

		while (true) {

			try {

				piece();

			} catch (SocketException e1) {

				LOGGER.warn(e1.getMessage(), e1);

				try {
					Thread.sleep(duration());
				} catch (InterruptedException e) {
					return;
				}

			} catch (Exception e2) {

				LOGGER.warn("Exception!", e2);
			}
		}
	}
}
